<!DOCTYPE HTML>
<html>
<head>
    <!-- twitter bootstrap CSS stylesheet - included to make things pretty, not needed or used by cornerstone -->
    <link href="../bootstrap.min.css" rel="stylesheet">

    <link href="../cornerstone.min.css" rel="stylesheet">

</head>
<body>
<div class="container">

    <div class="page-header">
        <h1>Example of displaying a WADO-RS RetreiveFrame response using Cornerstone</h1>
        <p class="lead">
            Enter a WADO-RS URL to a SOP Instance.
        </p>
    </div>

    <div id="loadProgress">Image Load Progress:</div>

    <div class="row">
        <form class="form-horizontal">
            <div class="form-group">

                <label class="control-label col-sm-1" for="apikey">APIKEY</label>
                <div class="col-sm-8">
                    <input class="form-control" type="text" id="apikey" placeholder="APIKEY" value="">
                </div>
             </div>
             <div class="form-group">
                <label class="control-label col-sm-1" for="wadoURL">URL</label>
                <div class="col-sm-8">
                    https://api.hackathon.siim.org/dicomweb/studies/1.3.6.1.4.1.14519.5.2.1.7777.9002.198875685720513246512710453733/series/1.3.6.1.4.1.14519.5.2.1.7777.9002.207203214132667549392101803048/instances/1.3.6.1.4.1.14519.5.2.1.7777.9002.327873213718058651550666129029/frames/1
                    <input class="form-control" type="text" id="wadoURL" placeholder="Enter WADO URL" value="https://raw.githubusercontent.com/chafey/cornerstoneWADOImageLoader/master/testImages/wadors">
                </div>
             </div>
            <div class="form-group">
                <div class="col-sm-3">
                    <button class="form-control" type="button" id="downloadAndView" class="btn btn-primary">Download and View</button>
                </div>
            </div>
        </form>
    </div>

    <div style="width:512px;height:512px;position:relative;color: white;display:inline-block;border-style:solid;border-color:black;"
         oncontextmenu="return false"
         class='disable-selection noIbar'
         unselectable='on'
         onselectstart='return false;'
         onmousedown='return false;'>
        <div id="dicomImage"
             style="width:512px;height:512px;top:0px;left:0px; position:absolute">
        </div>
    </div>
</div>
</body>


<!-- jquery - currently a dependency and thus required for using cornerstoneWADOImageLoader -->
<script src="../jquery.min.js"></script>

<!-- bootstrap -->
<script src="../bootstrap.min.js"></script>

<!-- include the cornerstone library -->
<script src="../cornerstone.min.js"></script>
<SCRIPT src="../cornerstoneMath.js"></SCRIPT>
<SCRIPT src="../cornerstoneTools.js"></SCRIPT>

<!-- include the dicomParser library as the WADO image loader depends on it -->
<script src="../dicomParser.min.js"></script>

<!-- BEGIN Optional Codecs -->

<!-- OpenJPEG based jpeg 2000 codec -->
<script src="../../codecs/openJPEG-FixedMemory.js"></script>

<!-- PDF.js based jpeg 2000 codec -->
<!-- NOTE: do not load the OpenJPEG codec if you use this one -->
<!--<script src="../../codecs/jpx.min.js"></script>-->

<!-- JPEG-LS codec -->
<script src="../../codecs/charLS-FixedMemory-browser.js"></script>

<!-- JPEG Lossless codec -->
<script src="../../codecs/jpegLossless.js"></script>

<!-- JPEG Baseline codec -->
<script src="../../codecs/jpeg.js"></script>

<!-- Deflate transfer syntax codec -->
<script src="../../codecs/pako.min.js"></script>

<!-- END Optional Codecs -->

<!-- include the cornerstoneWADOImageLoader library -->
<script src="../../dist/cornerstoneWADOImageLoader.js"></script>

<script>

    cornerstoneWADOImageLoader.configure({
        beforeSend: function(xhr) {
            // Add custom headers here (e.g. auth tokens)
            var apiKey = $('#apikey').val();
            if(apiKey && apiKey.length) {
                xhr.setRequestHeader('APIKEY', apiKey);
            }
        }
    });


    var loaded = false;

    function loadAndViewImage(imageId) {
        var element = $('#dicomImage').get(0);
        //try {
        cornerstone.loadImage(imageId).then(function(image) {
            console.log(image);
            var viewport = cornerstone.getDefaultViewportForImage(element, image);
            cornerstone.displayImage(element, image, viewport);
            if(loaded === false) {
                cornerstoneTools.mouseInput.enable(element);
                cornerstoneTools.mouseWheelInput.enable(element);
                cornerstoneTools.wwwc.activate(element, 1); // ww/wc is the default tool for left mouse button
                cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
                cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
                cornerstoneTools.zoomWheel.activate(element); // zoom is the default tool for middle mouse wheel
                loaded = true;
            }
        }, function(err) {
            alert(err);
        });
        /*}
         catch(err) {
         alert(err);
         }*/
    }

    function getImageFrameURI(metadataURI, metadata) {
        // Use the BulkDataURI if present int the metadata
        if(metadata["7FE00010"] && metadata["7FE00010"].BulkDataURI) {
            return metadata["7FE00010"].BulkDataURI
        }

        // fall back to using frame #1
        return metadataURI + '/frames/1';
    }


    function downloadAndView()
    {
        var url = $('#wadoURL').val();
        var metadataURI = url + "/metadata";
        $.ajax({
            url: metadataURI,
            headers: {
                accept: 'application/json'
            }
        }).done(function(data) {
            // Make sure it's a JSON document
            data = JSON.parse(data);

            console.log(data);

            var metadata = data[0];

            var imageFrameURI = getImageFrameURI(metadataURI, metadata);
            var imageId = 'wadors:' + imageFrameURI;

            cornerstoneWADOImageLoader.wadors.metaDataManager.add(imageId, metadata);

            // image enable the dicomImage element and activate a few tools
            loadAndViewImage(imageId);
        });
    }

    $(cornerstone.events).on('CornerstoneImageLoadProgress', function(event, eventData) {
        $('#loadProgress').text('Image Load Progress: ' + eventData.percentComplete + "%");
    });

    $(document).ready(function() {

        var element = $('#dicomImage').get(0);
        cornerstone.enable(element);

        $('#downloadAndView').click(function(e) {
            downloadAndView();
        });

        $('form').submit(function() {
            downloadAndView();
            return false;
        });

        $('#selectFile').on('change', function(e) {
            // Add the file to the cornerstoneFileImageLoader and get unique
            // number for that file
            var file = e.target.files[0];
            var imageId = cornerstoneWADOImageLoader.fileManager.add(file);
            loadAndViewImage(imageId);
        });
    });

</script>
</html>
